package com.rjkj.medicalwaste.ui.collect

import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.adapter.OnMultiClickListener
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.base.addOneGarbage
import com.rjkj.medicalwaste.bean.Decoder04Bean
import com.rjkj.medicalwaste.bean.MedicalWasteType
import com.rjkj.medicalwaste.bean.UserBean
import com.rjkj.medicalwaste.databinding.FragmentCollectOneBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.ui.my.NumberEditInputFilter
import com.rjkj.medicalwaste.utils.Encoder03Small
import com.rjkj.medicalwaste.utils.TimeUtils
import com.rjkj.medicalwaste.viewmodels.BluetoothControlViewModel
import com.rjkj.medicalwaste.viewmodels.CollectMainViewModel
import com.rjkj.medicalwaste.viewmodels.CollectOneViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class CollectOneFragment : BaseFragment<FragmentCollectOneBinding>(), View.OnClickListener {
    private val bluetoothControlViewModel: BluetoothControlViewModel by activityViewModels()
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private val collectOneViewModel: CollectOneViewModel by viewModels {
        MainViewModelProvider.providerCollectOneModel(requireContext())
    }
    private val viewModel: CollectMainViewModel by activityViewModels {
        MainViewModelProvider.providerCollectMainModel(requireContext())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentCollectOneBinding.inflate(inflater, container, false)
        onSubscribeUi(binding)
        binding.bluetoothData = bluetoothControlViewModel
        binding.userData = userViewModel
        binding.lifecycleOwner = viewLifecycleOwner
        return binding.root
    }

    override fun onSubscribeUi(binding: FragmentCollectOneBinding) {
        Log.e(TAG, "userViewModel: $userViewModel")
        if (userViewModel.setting.value?.infoMode == 1) {
            binding.tvWeight.setOnClickListener {
                addWeightDialog()
            }
        } else {
            binding.tvWeight.setOnLongClickListener {
                addWeightDialog()
                false
            }
        }
        initTip(collectOneViewModel)
        binding.imBack.setOnClickListener {
            requireActivity().onBackPressed()
        }
        bluetoothControlViewModel.startRec()
        binding.tvZero.setOnClickListener {
            bluetoothControlViewModel.zeroRec()
        }
        viewModel.list.observe(viewLifecycleOwner) {
            binding.tvNum.text = it.filter { value ->
                !value.fromControlBox
            }.size.toString()
        }

        val value = object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                if (v != null) {
                    when (v.id) {
                        R.id.bt_xg -> addGarbage(MedicalWasteType.XG)
                        R.id.bt_grx -> addGarbage(MedicalWasteType.GRX)
                        R.id.bt_ssx -> addGarbage(MedicalWasteType.SSX)
                        R.id.bt_blx -> addGarbage(MedicalWasteType.BLX)
                        R.id.bt_hxx -> addGarbage(MedicalWasteType.HXX)
                        R.id.bt_ywx -> addGarbage(MedicalWasteType.YWX)
                        R.id.bt_tp -> addNumDialog(MedicalWasteType.TP)
                        R.id.bt_lqh -> addNumDialog(MedicalWasteType.LQH)
                    }
                }
            }

            override fun onInvalidClick(long: Long) {
                val pi = long.div(1000)
                showTip("请${pi}秒后再试")
            }


        }
        binding.btGrx.setOnClickListener(value)
        binding.btSsx.setOnClickListener(value)
        binding.btBlx.setOnClickListener(value)
        binding.btHxx.setOnClickListener(value)
        binding.btYwx.setOnClickListener(value)
        binding.btTp.setOnClickListener(value)
        binding.btLqh.setOnClickListener(value)
        binding.btXg.setOnClickListener(value)
    }

    /**
     * 添加医废到List并打印 供上个页面使用
     * @param medicalWasteType MedicalWasteType
     * @param count Int
     */
    private fun addGarbage(medicalWasteType: MedicalWasteType, count: Int = 0) {
        Log.e(TAG, "addGarbage: ")
        val timeStr = TimeUtils.getTimeStr()
        val weight = bluetoothControlViewModel.decoder04Bean.value?.weight ?: "0"
        if (collectOneViewModel.time == timeStr) {
            showTip("请稍后再试")
            return
        } else {
            collectOneViewModel.time = timeStr
        }

        if (weight.toFloat() < 0) {
            showTip("重量为负")
            return
        } else if (weight.toFloat().compareTo(0) == 0) {
            showTip("重量为0")
            return
        }
        lifecycleScope.launch {
            val department = userViewModel.departmentUser.value ?: UserBean()
            val nurse = userViewModel.nurseUser.value ?: UserBean()
            val user = userViewModel.cleanerUser
            val format = String.format("%04d", weight.replace(".", "").toInt())
            val serialNum = userViewModel.getSerial()
            Log.e(TAG, "addGarbage:$serialNum ")
            val garbageQRCode = "1" +
                    timeStr +
                    serialNum +
                    medicalWasteType.num.toString() +
                    format +
                    department.qrcode.substring(12) +
                    nurse.qrcode.substring(12) +
                    user.qrcode.substring(12) +
                    "B"
            Log.e(TAG, "addGarbage: $garbageQRCode")
            val addGarbage = addOneGarbage(
                code = garbageQRCode,
                weight = weight,
                medicalWasteType = medicalWasteType,
                hospitalIdStr = userViewModel.hospitalId.value ?: "",
                user = user,
                nurse = nurse,
                department = department,
                garbageDeviceSN = userViewModel.getSerial(),
                garbageCount = count,
                hospitalName = userViewModel.hospitalName.value ?: ""
            )
            viewModel.addGarbageToList(addGarbage)
            val encoder03Small = Encoder03Small()
            //袋模式1，箱模式：2
            encoder03Small.setQRcode("1", garbageQRCode, userViewModel.hospitalId.value)
            encoder03Small.setGarbage(
                userViewModel.hospitalName.value,
                department.name,
                weight + "KG",
                medicalWasteType.typeName,
                user.name,
                nurse.name,
                TimeUtils.getYMDHMSTime()
            )
            bluetoothControlViewModel.printRec(encoder03Small)
            LiveDataBus.get().with("Print").postValue(encoder03Small)
            showTip("收集成功")
        }


    }

    private fun addNumDialog(medicalWasteType: MedicalWasteType) {
        val et = EditText(requireContext())
        et.inputType = InputType.TYPE_CLASS_NUMBER
        et.filters = arrayOf(NumberEditInputFilter(100, 0))
        AlertDialog.Builder(requireContext())
            .setTitle("请输入数量")
            .setView(et)
            .setPositiveButton("确定", DialogInterface.OnClickListener { _, i -> //按下确定键后的事件
                val toString = et.text.toString()
                if (toString.isNotEmpty()) {
                    addGarbage(medicalWasteType, toString.toInt())
                }
            }).setNegativeButton("取消", null).show()
    }

    private fun addWeightDialog() {
        val et = EditText(requireContext())
        et.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        et.filters = arrayOf(NumberEditInputFilter(100))
        AlertDialog.Builder(requireContext())
            .setTitle("请输入重量")
            .setView(et)
            .setPositiveButton("确定", DialogInterface.OnClickListener { _, i -> //按下确定键后的事件
                val toString = et.text.toString()
                if (toString.isNotEmpty()) {
                    bluetoothControlViewModel.decoder04Bean.value = Decoder04Bean().apply {
                        weight = toString
                    }
                } else {
                    showTip("未输入重量")
                }
            }).setNegativeButton("取消", null).show()
    }


    override fun onDestroyView() {
        bluetoothControlViewModel.stopRec()
        super.onDestroyView()
    }

    override fun onClick(v: View) {
    }

}